﻿using SelfHosting.Filters;
using SelfHosting.Handlers;
using log4net.Config;
using Microsoft.Practices.Unity;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dependencies;
using System.Web.Http.SelfHost;
using System.Web.Http.SelfHost.Channels;
using System.Web.Http.Tracing;

namespace SelfHosting
{
    /// <summary>
    /// La classe de configuration pour les services Http
    /// </summary>
    public class MySelfHostConfiguration : HttpSelfHostConfiguration
    {
        #region Constructeur

        /// <summary>
        /// Initialise une nouvelle instance de la classe AtalSelfHostConfiguration
        /// </summary>
        /// <param name="baseAddress">adresse de base pour les services</param>
        public MySelfHostConfiguration(string baseAddress)
            : base(baseAddress)
        {
            Routes.MapHttpRoute(
               name: "ActionApi",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional, action = "Default" }
           );
            MaxReceivedMessageSize = 1024 * 1024 * 20;
            Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK";
            XmlConfigurator.Configure();
            DependencyResolver = GetDependencyResolver();
            Filters.Add(new ExceptionHandlingAttribute());
            MessageHandlers.Insert(0, new CompressionHandler());
        }

        #endregion

        #region Méthodes

        private IDependencyResolver GetDependencyResolver()
        {
            var container = new UnityContainer();
            container.RegisterType<IServiceProvider, ServiceProvider>(new HierarchicalLifetimeManager());

            // Enregistrement des contrôleurs
            var apiControllerType = typeof(IHttpController);
            foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
            {
                if (type.IsClass && !type.IsAbstract && type.IsPublic && apiControllerType.IsAssignableFrom(type))
                {
                    container.RegisterType(type);
                }
            }
            Services.Replace(typeof(ITraceWriter), new Log4NetTraceWriter());
            return new UnityDependencyResolver(container);
        }

        #endregion
    }
}
